const express=require('express');
const mongoose = require('mongoose');
const articleSchema = require('../model/articleDb');
const commentSchema = require('../model/comment');
const urlLib = require('url');//用于解析get所携带的参数


//4.连接数据库（mongoodb）
mongoose.connect("mongodb://localhost/myblog");
var db = mongoose.connection;
db.on('error', function () {
  throw new Error('unable to connect to database at ');
});
db.on('open', function () {
  console.log("连接数据库成功");
});

var article= db.model('article1',articleSchema);
var comments= db.model('comments',commentSchema);


module.exports=function (){
  var router=express.Router();
  
  //按照分类查询文章
  router.get('/select', function (req, res){
      var count = urlLib.parse(req.url,true).query.count;
      // var type = urlLib.parse(req.url,true).query.type;
      // var arg = {};
      // if(type!=undefined){
      //   arg = {
      //     type:type
      //   }
      // }else{
      //   arg={};
      // }
      article.find({},null,{limit:parseInt(count)},function(error,data){
        if(error){
          res.send({state:false,mes:"查询失败"}).end();
        }else{
          res.send({state:true,mes:data}).end();
        }
      });
  	// res.send(urlLib.parse(req.url,true));//true表示将参数解析成json格式
    // res.render('./1.ejs', {title: '我是标题', a: 12, b: 5}); //使用render时需要设置模板引擎，否则会报错
  });

  //按照id查询一篇
  router.get('/selectOne', function (req, res){
      var id = urlLib.parse(req.url,true).query.id;
      article.find({_id:id},function(error,data){
        if(error){
          res.send({state:false,mes:"查询失败"}).end();
        }else{
          res.send({state:true,mes:data}).end();
        }
      });
  });

  //添加评论
  router.post('/addcomment', function (req, res){
      var articleId = req.body.articleId;
      var author = req.body.author;
      var content = req.body.content;
      var time = new Date();

      var newcomment = {
        articleId:articleId,
        author:author,
        content:content,
        time:time
      };
      var commentEntity = new comments(newcomment);
      commentEntity.save(function(error,data){
        if(error){
          res.send("评论失败！").end();
        }else{
          res.send("评论成功！").end();
        }
      });
  });

  //删除评论
  router.get('/delcomment', function (req, res,next){
      var commentleId = urlLib.parse(req.url,true).query.commentleId;
      var author = urlLib.parse(req.url,true).query.author;

      comments.find({_id:commentleId},function(error,data){
        if(error){
          res.send("删除失败！"+"======>"+error).end();
        }else{
          if(data[0].author==author){
            next();
          }else{
            res.send("你没有权限").end();
          }
        }
      });
  },function(req, res,next){
    var commentleId = urlLib.parse(req.url,true).query.commentleId;
    comments.remove({_id:commentleId},function(error,data){
      if(error){
        res.send("删除失败！"+"======>"+error).end();
      }else{
        res.send("删除成功！").end();
      }
    });
  });

  
  //查看评论
  router.get('/getcomment', function (req, res){
      var articleId = urlLib.parse(req.url,true).query.articleId;
      comments.find({articleId:articleId},function(error,data){
        if(error){
          res.send("查询评论失败！"+"======>"+error).end();
        }else{
          res.send(data).end();
        }
      });
  });
  return router;
};
